<template>
  <div class="comment">
    <div style="font-size: 24px;font-weight: 600;padding: 20px;">
        <span >评论</span>
    </div>
    <div class="commentBox">
        <div class="box-top">
            <div class="box-img">
                <img style="border-radius: 50%;box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);" width="48px" height="48px" src="../assets/ph.png" alt="Image">
            </div>
            <el-form ref="form" :model="form" :rules="rules" style="width: 91%;">
                <el-input
                class="textarea"
                type="textarea"
                @focus="handleFocus"
                @blur="blur"
                maxlength="100"
                show-word-limit
                placeholder="请输入内容"
                v-model="form.content">
                </el-input>
            </el-form>
        </div>
        <div class="box-bot" :class="{ 'hide': isHidden }" >
            <div class="box-em">
                <Emoji @output="output"></Emoji>
            </div>
            <div  class="box-send" >
                <el-button type="primary" size="small" @click="submitForm">发布</el-button>
            </div>
        </div>
    </div>

    <el-divider></el-divider>

    <div class="commentBox" v-for="item,index in commentList " :key="index">
        <div class="box-top">
            <div class="article-img">
                <img style="border-radius: 50%;box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);margin-top: 25px;" width="48px" height="48px" src="../assets/ph.png" alt="Image">
            </div>
            <div class="content">
                <div class="userInfo">{{ item.createBy }}</div>
                <div class="content-box">
                    {{ item.content }}
                </div>
                <div class="handle userInfo">
                    <span>{{ formatDate(item.createTime)  }}</span>
                    <span ><el-button type="text"  size="mini" @click="showReplyInput(item)">回复</el-button></span>
                </div>
            </div>
        </div>            
        <div class="commentBoxSon" v-for="childItem,indexItem in item.children " :key="indexItem">
            <div class="box-top">
                <div class="article-img">
                    <img style="border-radius: 50%;box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);margin-top: 25px;" width="48px" height="48px" src="../assets/ph.png" alt="Image">
                </div>
                <div class="content">
                    <div class="userInfo">{{ childItem.createBy }}</div>
                    <div class="content-box">
                        {{ childItem.content }}
                    </div>
                    <div class="handle userInfo">
                        <span>{{ formatDate(childItem.createTime) }}</span>
                        <span ><el-button type="text" size="mini"  @click="showReplyInput(item,childItem)">回复</el-button></span>
                    </div>
                    
                </div>
            </div>      
        </div> 

        <input-component :show="showItemId === item.cid"
                         :value="inputComment"
                         :toComment="name"
                         :toId="id"
                         @cancel="cancelInput"
                         @confirm="commitComment">
        </input-component>



    </div>
    

  </div>
</template>

<script>
import axios from 'axios';
import Emoji from '@/components/Emoji'
import InputComponent from './InputComponent'

import jwtDecode from 'jwt-decode';

export default {
    name:"Comment",
    components: {
      Emoji,
      "input-component": InputComponent
    },
    props:{
        articleId:{
            type:String,
            default:null
        },
    },
    data() {
        return {
            textarea:"",
            //发布隐藏
            isHidden: false,
            //回复隐藏
            isReplyHidden:false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                articleId: null,
            },
            // 评论信息表格数据
            commentList: [],
            // 表单参数
            form: {
                artId: null,
                parentId:null,
                mainId: null,
                userId: null,
                content: null
            },
            // 表单校验
            rules: {
                content: [
                { required: true, message: "评论内容不能为空", trigger: "blur" }
                ],
            },
            cursorIndexStart: null,//光标选中开始的位置
            cursorIndexEnd: null,//光标选中结束的位置
            userInfo: null,
            //评论总数
            total:0,

            //子集评论
            inputComment: '',
            name: '',
            id: null,
            showItemId: '',
            commentLikeForm: {},

        };
    },
    created() {
        const token = localStorage.getItem('token');
        if (token) {
        const decoded = jwtDecode(token);
        this.form.userId = decoded.userId; // 从JWT中获取用户ID
        }

        this.getList();
    },
    methods: {
        handleFocus() {
            this.isHidden = true;
        },

        blur(e){
            this.cursorIndexStart = e.srcElement.selectionStart  // 获取input输入框失去焦点时光标选中开始的位置
            this.cursorIndexEnd = e.srcElement.selectionEnd  // 获取input输入框失去焦点时光标选中结束的位置
        },

        output(val) {
            if (this.cursorIndexStart !== null && this.form.content) {
            //如果 文本域获取了焦点, 则在光标位置处插入对应字段内容
            this.form.content = this.form.content.substring(0, this.cursorIndexStart) + val + this.form.content.substring(this.cursorIndexEnd)
            } else {
            // 如果 文本域未获取焦点, 则在字符串末尾处插入对应字段内容
            this.form.content = this.form.content?this.form.content:'' + val
            }
        },

        /** 查询评论信息列表 */
        getList() {

            axios.get('/api/comment/list', 
            {
            headers: {'Authorization': `Bearer ${localStorage.getItem('token')}`},
            params: { artId: this.articleId }
            })
            .then(response => {
            console.log("comment:", response.data);
            this.commentList = response.data;
            console.log(this.commentList)
            })
            .catch(error => {
            console.error("获取评论失败:", error);
            });


        },

        // 表单重置
        reset() {
        this.form = {
            articleId:null,
            content: null
        };
        this.resetForm("form");
        },

        /** 提交按钮 */
        submitForm() {
            this.isHidden = false;
            this.form.artId = parseInt(this.articleId);

            console.log(this.form)
            axios({
                method: 'post',
                url: '/api/comment/add',
                data: this.form,
                headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            })
            .then(response => {
                console.log("comment:", response.data);
                this.$message.success('感谢您的精彩发言！！！');
                this.getList();
                this.form.content = null;
            })
            .catch(error => {
                console.error("评论失败:", error);
            });





        },

        showReplyInput(item,childItem){
            
            if (childItem) {
                this.inputComment = "";
                this.name = "回复@" + childItem.createBy + ":";
                this.id = childItem.cid;
            } else {
                this.inputComment = '';
                this.name = '写下你的评论';
                this.id = item.cid;
                console.log(item.cId)
            }
            this.showItemId = item.cid;
        },

        cancelInput() {
            this.showItemId = ''
        },

        /**
         * 提交评论
         */
        commitComment(value) {
            console.log(value);
            console.log('-------------------------------------------------------')
            this.form.content = value.inputComment;
            this.form.parentId = value.id;
            this.form.artId = this.articleId;
            axios({
                method: 'post',
                url: '/api/comment/add',
                data: this.form,
                headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            })
            .then(response => {
                console.log("comment:", response.data);
                this.$message.success('感谢您的精彩发言！！！');
                this.getList();
                this.form.content = null;
            })
            .catch(error => {
                console.error("评论失败:", error);
            });

        },

        /**
       * 点击取消按钮
       */
      cancelInput() {
        this.showItemId = ''
      },



      formatDate(date) {
      if (date) {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
        return new Date(date).toLocaleDateString(undefined, options);
      }
      return '';
    },

    }
}

</script>

<style scoped >

.comment {
    width: 80%;
    margin-top: 10px;
    min-height: 150px;
    background-color: white !important;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.commentBox {
    padding: 10px 20px;
    min-height: 54px;
    /* background-color: #C9CCD0; */
}

.commentBoxSon {
    padding-top: 20px;
    padding-left: 68px;
    min-height: 54px;
}

.box-top {
    display: flex;
    /* background-color: antiquewhite; */
}

.box-img {
    height: 54px;
    /* background-color: black; */
}

.textarea {
    margin-left: 20px;
}


.box-bot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 0px;
    overflow: hidden;
    transition: height 0.5s ease;
}

.box-em {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    margin-left: 70px;
    border: 1px solid #E7E7E7;
    border-radius: 4px;
}

.box-send {
    float: right;
    height: 40px;
    line-height: 40px;
    margin-right: 80px;
}

.hide{
    height: 40px;
}

.content {
    width: 100%;
    margin-left: 20px;
}

.userInfo {
    display: flex;
    margin-top: 5px;
    font-size: 13px;
    font-weight: 500;
    color: #61666d;
}

.content-box {
    width: 100%;
    margin-top: 5px;
    font-size: 15px;
    line-height: 2;
    padding: 10px;
    border-radius: 5px;
    background-color: rgb(241,242,243);
}
.handle span {
    display: flex;
    align-items: center;
    height: 20px;
    line-height: 20px;
    margin-right: 25px;
}

</style>
